package com.example.baseutils;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.BatteryManager;
import android.os.Build;
import android.util.Log;


import com.example.baseutils.application.BaseApplication;

import java.io.IOException;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

import static android.content.Context.BATTERY_SERVICE;

/**
 * AppUtils
 * lp
 * 2019/5/27
 */
public class AppUtils {

    /**
     * 返回当前程序版本名
     */
    public static String getAppVersionName(Context context) {
        String versionName = "";
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
            //versioncode = pi.versionCode;
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
        }
        return versionName;
    }

    public static boolean isNanopi(String target) {
        if (target == null) {
            target = "nanopi";
        }

        if (Build.BOARD.contains(target)) {
            return true;
        }
        return false;
    }

    /**
     * 获取apk文件的版本号
     *
     * @param filePath apk路径
     * @return
     */
    public static String getAPKVersionName(Context context, String filePath) {
        if (filePath == null)
            return null;
        if (!FileUtil.isFileExist(filePath))
            return null;

        PackageManager packageManager = context.getPackageManager();
        PackageInfo packageInfo = packageManager.getPackageArchiveInfo(filePath, PackageManager.GET_ACTIVITIES);
        if (packageInfo == null)
            return null;
        return packageInfo.versionName;
    }

    private static String deivceMac = null;

    /**
     * 根据wifi信息获取本地mac
     *
     * @return
     */
    public static String getLocalMacAddressFromWifiInfo() {
        String sign=AppConstants.SING_TYPE;
        if (deivceMac != null) {
            Log.i("mac", "mac: " + deivceMac);
            return deivceMac.toLowerCase();
        }
        deivceMac = PreferncesUtilKt.read(PreferncesUtilKt.getMySharedPreferences(), Constance.DEVICEID, "02:00:00:00:00:00");
        if (!deivceMac.equals("02:00:00:00:00:00")) {
            deivceMac = deivceMac+"_"+sign;
            Log.i("mac", "mac: " + deivceMac);
            return deivceMac.toLowerCase();
        }
        String tempMac = null;
        //大于安卓5.1
        if (Build.VERSION.SDK_INT >= 19) {
            try {
                List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
                for (NetworkInterface nif : all) {
                    if (!nif.getName().equalsIgnoreCase("wlan0")) continue;

                    byte[] macBytes = nif.getHardwareAddress();
                    if (macBytes != null) {
                        StringBuilder res1 = new StringBuilder();
                        for (byte b : macBytes) {
                            res1.append(String.format("%02X:", b));
                        }

                        if (res1.length() > 0) {
                            res1.deleteCharAt(res1.length() - 1);
                        }
                        String mac = String.valueOf(res1);
                        mac = mac.replace(":", "");
                        tempMac = mac;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (tempMac == null || tempMac.equals("02:00:00:00:00:00")) {
            tempMac = UUID.randomUUID().toString();
        }
        Log.i("mac", tempMac);
        Log.i("mac", "初次更新mac地址");
        PreferncesUtilKt.getMySharedPreferences().edit().putString(Constance.DEVICEID, tempMac).apply();
        deivceMac  =tempMac+"_"+sign;
        return deivceMac.toLowerCase();
    }
    /**
     * 根据wifi信息获取本地mac
     *7.0权限
     * @param
     * @return
     *//*
    public static String getMacFromHardware() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!nif.getName().equalsIgnoreCase("wlan0")) continue;

                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null) {
                    return "";
                }

                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02X:", b));
                }

                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                }
                return res1.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "02:00:00:00:00:00";
    }*/

    /**
     * 获取进程名方法
     */
    public static String getProcessName(Context cxt, int pid) {
        ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
        if (runningApps != null && !runningApps.isEmpty()) {
            for (ActivityManager.RunningAppProcessInfo procInfo : runningApps) {
                if (procInfo.pid == pid) {
                    return procInfo.processName;
                }
            }
        }

        return null;
    }

    /**
     * 获取当前电量
     */
    public static int getNowBattary(Context context) {
        BatteryManager batteryManager = (BatteryManager) context.getSystemService(BATTERY_SERVICE);
        int battery = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
        return battery;
    }

    /**
     * 获取当前launcher
     */
    public static String getHomeLauncher(Context context) {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        ResolveInfo resolveInfo = context.getPackageManager().resolveActivity(intent, 0);
        String currentHomePackage = resolveInfo.activityInfo.packageName;
        return currentHomePackage;
    }


    /**
     * 判断是否是默认桌面
     *
     * @return
     */
    public static boolean isDefaultHome(Context mContext) {
        Intent intent = new Intent(Intent.ACTION_MAIN);//Intent.ACTION_VIEW
        intent.addCategory("android.intent.category.HOME");
        intent.addCategory("android.intent.category.DEFAULT");
        PackageManager pm = mContext.getPackageManager();
        ResolveInfo info = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
        boolean isDefault = mContext.getPackageName().equals(info.activityInfo.packageName);

        return isDefault;
    }

    /**
     * 设置activity为默认桌面
     *
     * @param activityName
     */
    public static void setDefaultLauncher(Context mContext,String activityName) {
        PackageManager pm = mContext.getPackageManager();
        String examplePackageName = "com.example.studyrobot"; //请修改为需要设置的 package name
        String exampleActivityName = activityName; //请修改为需要设置的 launcher activity name

        ComponentName defaultLauncher = null;
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);

        List<ResolveInfo> resolveInfoList =
                pm.queryIntentActivities(intent, 0);
        if (resolveInfoList != null) {
            int size = resolveInfoList.size();
            for (int j = 0; j < size; ) {
                final ResolveInfo r = resolveInfoList.get(j);
                if (!r.activityInfo.packageName.equals(examplePackageName)) {
                    resolveInfoList.remove(j);
                    size -= 1;
                } else {
                    j++;
                }
            }

            defaultLauncher = new ComponentName(examplePackageName, exampleActivityName);

            ComponentName[] set = new ComponentName[]{new ComponentName("com.android.launcher", "com.android.launcher2.Launcher"), defaultLauncher};
            IntentFilter filter = new IntentFilter();
            filter.addAction(Intent.ACTION_MAIN);
            filter.addCategory(Intent.CATEGORY_HOME);
            filter.addCategory(Intent.CATEGORY_DEFAULT);

            //待设置的桌面要在xml里声明具有HOME属性
            pm.clearPackagePreferredActivities("com.android.launcher");
            pm.addPreferredActivity(filter, IntentFilter.MATCH_CATEGORY_EMPTY, set, defaultLauncher);
        }
    }
    public static List<String> getPkgListNew() {
        List<String> packages = new ArrayList<String>();
        try {
            List<PackageInfo> packageInfos = BaseApplication.getInstance().getPackageManager().getInstalledPackages(PackageManager.GET_ACTIVITIES |
                    PackageManager.GET_SERVICES);

            for (PackageInfo info : packageInfos) {
                String pkg = info.packageName;
                if (!isSystemApp(info)) {
                    packages.add(pkg);
                }
            }
        } catch (Throwable t) {
            t.printStackTrace();
        }
        Log.i("getPkgListNew", "getPkgListNew: " + Arrays.toString(packages.toArray()));
        return packages;
    }
    public static boolean isSystemApp(PackageInfo pi) {
        boolean isSysApp = (pi.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 1;
        boolean isSysUpd = (pi.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) == 1;
        return isSysApp || isSysUpd;
    }
    /**
     * 关机
     * */
    public static void shoutDownSystem(){
        try {
            Runtime.getRuntime().exec("reboot -p"); //关机
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
